<?php
/**
 *
 *@author Dmitry
 */
class Backend_TemplateController extends RCMS_Core_BaseController {

    /**
     * Path for save image
     * @var <string>
     */
    private $_savePathPreviewImage;

    private $_currentTheme;

    public function init()
    {
        parent::init();
        $this->_checkLogin();
        $this->_model = new Default_Model_TemplateModel();
        $this->_currentTheme = $this->_model->selectCurrentTheme();
        if($this->_currentTheme == '')
        {
            $this->_currentTheme = 'default';
        }
        $this->_savePathPreviewImage = $this->_config->website->website->path . 'public/themes/' . $this->_currentTheme . '/images/templatepreview/';
    }

    public function indexAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout->disableLayout();
    }

    /**
     * Add new template
     * @return void
     */
    public function addAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $websitePath = $this->_config->website->website->path;
        $templateThemesPath = $this->_config->website->website->themesPath;
        $templatePreviewFolderName = $this->_config->template->template->template_preview_folder_name;
        $templateImagesFolderName = $this->_config->template->template->themes_images_folder;

        $form = new RCMS_Form_TemplateForm();
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/addtemplate.phtml'))
            ));
        $this->view->form = $form;        
        $this->view->currentTheme = $this->_currentTheme;

        if($this->getRequest()->isPost())
        {
            if($this->view->form->isValid($this->getRequest()->getParams()))
            {
                $name = $this->view->form->name->getValue();
                $name = strtolower(str_replace(" ","-",RCMS_Tools_FilesystemTools::trimInternalSpaces($name)));
                $existsName = (integer)$this->_model->selectTemplateExist($name);

                if ($existsName > 0)
                {
                    $this->view->error = true;
                    $this->view->message = 'This name already exist.';
                    $fullPathToTemplatePreview = $websitePath.$templateThemesPath.$this->_currentTheme."/".$templateImagesFolderName.$templatePreviewFolderName;
                    $imageName =$this->getRequest()->getParam('image_name');
                    if($imageName){
                        unlink($fullPathToTemplatePreview.$imageName);
                    }
                }
                else
                {
                    // create new template and set data
                    $newTemplate = new RCMS_Object_Template_Template();
                    $newTemplate->setName($name);
                    $newTemplate->setContent($this->view->form->content->getValue());
                    $newTemplate->setTheme($this->_currentTheme);
                    $newTemplate->setPreviewImage($this->getRequest()->getParam('image_name'));
                    //save new template
                    $fullPathToTemplatePreview = $websitePath.$templateThemesPath.$newTemplate->getTheme()."/".$templateImagesFolderName.$templatePreviewFolderName;
                    $imageName = $newTemplate->getPreviewImage();

                    if($imageName){
                        $arr = explode(".", $imageName);
                        $imageExtension = $arr[1];
                        $oldImagePath = $fullPathToTemplatePreview.$imageName;

                        $newImageFileName = str_replace(" ", "-", trim(strtolower($newTemplate->getName())));
                        $newImagePath = $fullPathToTemplatePreview.$newImageFileName.".".$imageExtension;
                        rename($oldImagePath, $newImagePath);
                        $newTemplate->setPreviewImage($newImageFileName.".".$imageExtension);
                    }
                    
                    $newTemplate->save();
                    unset($newTemplate);
                    $this->view->form->reset();
                    $this->view->success = true;
                    $this->view->message = "Your template was created, it will be available next time you create page. You can create another template, or simply close this window.";
                    //save fs
                    $path = $this->_config->website->website->path . $this->_config->website->website->themesPath . $this->_currentTheme;
                    $success = @file_put_contents($path . '/' . $name . '.html', $this->view->form->content->getValue());
                    if($success === false) {
                         $this->view->message .= "Can't save file ($path/$name.html').";
                    }                    
                }
            }
            else
            {
                $this->view->errorElements = $this->processErrors($this->view->form->getMessages());
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    /**
     * List templates
     * @return void
     */
    public function listAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $templates = $this->_model->selectAllTemplates();
        foreach ($templates as &$template){
            $template['name'] = ucfirst(strtolower(str_replace("-"," ",trim($template['name']))));
        }
        $websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;        
        $this->view->websiteUrl = $websiteUrl;
        $this->view->templates = $templates;
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    /**
     * Edit template
     * @return void
     */
    public function editAction()
    {
		$this->_cache->clean('all');
        $this->_helper->getHelper('layout')->disableLayout();
        $websitePath = $this->_config->website->website->path;
        $templateThemesPath = $this->_config->website->website->themesPath;
        $templatePreviewFolderName = $this->_config->template->template->template_preview_folder_name;
        $templateImagesFolderName = $this->_config->template->template->themes_images_folder;

        $form = new RCMS_Form_TemplateForm();
        $form->submit->setLabel('{%UPDATE TEMPLATE%}');
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/edittemplate.phtml'))
            ));        
        $this->view->form = $form;
        $this->view->currentTheme = $this->_currentTheme;

        //if got data across POST
        if($this->getRequest()->isPost() /*&&
            $this->getRequest()->getParam('submit') === 'UPDATE TEMPLATE'*/)
        {
            if($this->view->form->isValid($this->getRequest()->getParams()))
            {
                $name = $this->view->form->name->getValue();
                $name = strtolower(str_replace(" ","-",RCMS_Tools_FilesystemTools::trimInternalSpaces($name)));
                $existsName = $this->_model->selectTemplateByName($name);

                if(count($existsName) == 0 || (count($existsName) == 1  && $existsName[0]['id'] == $this->getRequest()->getParam('id')))
                {
                    $id = (integer) $this->getRequest()->getParam('id');
                    $template = new RCMS_Object_Template_Template($id);
                    $oldName = $template->getName();
                    $oldTemplatePreview = $template->getPreviewImage();
                    $template->setName($name);
                    $template->setId($id);
                    $template->setContent($this->view->form->content->getValue());
                    $template->setTheme($this->_currentTheme);
                    $template->setPreviewImage($this->getRequest()->getParam('image_name'));

                    $fullPathToTemplatePreview = $websitePath.$templateThemesPath.$template->getTheme()."/".$templateImagesFolderName.$templatePreviewFolderName;
                    $imageName = $template->getPreviewImage();

                    if(!empty ($imageName)){
                        $arr = explode(".", $imageName);
                        $imageExtension = $arr[1];

                        $oldImagePath = $fullPathToTemplatePreview.$imageName;
                        $newImageFileName = str_replace(" ", "-", trim(strtolower($template->getName())));
                        $newImagePath = $fullPathToTemplatePreview.$newImageFileName.".".$imageExtension;
                        $newTemplateName = str_replace(" ","-",trim($template->getName())).".".$arr[1];

                        if( preg_match('/^[0-9]+$/',$arr[0]))
                        {
                            if(isset($template) && !empty($oldTemplatePreview) )
                            {
                                @unlink($fullPathToTemplatePreview.$oldTemplatePreview);
                                clearstatcache();
                            }

                            if(!rename($oldImagePath, $newImagePath))
                            {
                                @unlink($fullPathToTemplatePreview.$template->getPreviewImage());
                                clearstatcache();
                            }
                        }else
                        {
                            if($newTemplateName!=$imageName)
                            {
                                rename($fullPathToTemplatePreview.$imageName, $fullPathToTemplatePreview.$newTemplateName);
                            }
                        }
                    }

                    if(isset($newImageFileName)){
                        $this->view->form->image_name->setValue($newImageFileName.".".$imageExtension);
                        $template->setPreviewImage($newImageFileName.".".$imageExtension);
                    }
                    $template->save();

                    //save fs
                    $path = $this->_config->website->website->path . $this->_config->website->website->themesPath . $this->_currentTheme;
                    if($oldName != $name){
                        rename($path . '/' . $oldName . '.html', $path . '/' . $name . '.html');
                    }
                    $this->view->success = true;
                    if(false === file_put_contents($path . '/' . $name . '.html', $this->view->form->content->getValue())){
                        $this->view->message = "Can't save file ($path/$name.html)<br />";
                    }
                }
                else
                {
                    $this->view->error = true;
                    $this->view->message = 'This name already exist';
                }
            }
            else
            {
                $this->view->errorElements = $this->processErrors($this->view->form->getMessages());
            }
        }
        else
        {
            $id = intval($this->getRequest()->getParam('id'));
            $template  = new RCMS_Object_Template_Template($id);
            //if do not have variable $id
            if($id === 0 || $template->getId() == 0)
            {
                $this->view->error = true;
                $this->view->message = 'Template not found';
                $this->view->form->name->setAttrib('disabled', 'disabled');
                $this->view->form->content->setAttrib('disabled', 'disabled');
                $this->view->form->templateuploadpic->setAttrib('disabled', 'disabled');
                $this->view->form->submit->setAttrib('disabled', 'disabled');
            }
            else
            {
                //else assign edit form
                $this->view->form->setValues($template);
                if($template->getName() == 'index' || $template->getName() == 'default' || $template->getName() == 'category')
                {
                    $this->view->form->name->setAttrib('readonly','readonly');
                }
                unset($template);
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

   

    /**
     * List templates for edit template
     * @return void
     */
    public function listtemlatesAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $currentTemplateName = '';
        $templates = $this->_model->selectAllTemplates();
        foreach ($templates as &$template){
            $template['name'] = ucfirst(strtolower(str_replace("-"," ",trim($template['name']))));
        }
        $currentTemplateName = $this->getRequest()->getParam('tname');
        $this->view->currentTemplateName = $currentTemplateName;
        $this->view->templates = $templates;
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    /**
     *
     * @method this method is processing errors from Page Form
     * @param <type> $array
     * @return <type>
     *
     */
    public function processErrors($array)
    {
        $messages = array();
        $htmlUl = "";


        foreach ($array as $key=>$value)
        {
            switch ($key)
            {
                case 'name':
                    if(isset($value['isEmpty']))
                    $messages[]="Template name field can't be empty.";
                    if(isset($value['stringLengthTooShort']))
                    $messages[]="Template name field is too short.";
                    if(isset($value['stringLengthTooLong']))
                    $messages[]="Template name field is too long.";
                    break;

                case 'content':
                    if(isset($value['isEmpty']))
                    $messages[]="Content text area can't be empty.";
                    break;
            }
        }
        if(!empty($messages))
        {
            $htmlUl = "<ul>";
            foreach ($messages as $message)
            {
                $htmlUl .= "<li>".$message."</li>";
            }
            $htmlUl .= "<ul>";
            return $htmlUl;
        }
        return null;
    }

	public function listvarsAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}
}
